<?php
namespace frontend\controllers;

use backend\models\BuildType;
use common\components\phpexecel\CommonFunc;
use frontend\models\PrfTzBrand;
use frontend\models\UserFavourite;
use Yii;
use yii\web\Controller;
use frontend\models\TaoZhuang;
use frontend\models\SysItem;
use yii\data\Pagination;
use yii\data\Sort;
use backend\models\GrpSpace;
use backend\models\GrpClass;
use backend\models\Fabric;
use backend\models\Material;
use backend\models\ItemPreview;
use backend\models\GrpStyle;
use backend\models\GrpColor;
use frontend\models\TaoZhuangPos;
use frontend\models\ItemPriceTable;
use frontend\models\UserShoppingCart;
use yii\db\ActiveRecord;
use frontend\models\LogUserFootprint;

class TzController extends Controller {
    public function actionIndex() {
        
        $get_space_id=yii::$app->request->get('space');
        $get_style_id=yii::$app->request->get('style');
        $get_color_id=yii::$app->request->get('color');
        $get_type_id =yii::$app->request->get('type');
        $get_brand_id=yii::$app->request->get('brand');
        $get_class_id=yii::$app->request->get('class');
        $get_order=yii::$app->request->get('order');
        //找我家
        $get_home_id=Yii::$app->request->get('home');

        //空间分类对象
        $space=GrpSpace::find()->where(['useing'=>1])->asArray()->all();
        //品牌分类对象
        $brand=ActiveRecord::findBySql("SELECT DISTINCT state_tree FROM `taozhuang`")->asArray()->all();
        $tzBrand = PrfTzBrand::find()->select(['name','id'])->where(['open' => 1])->indexBy('id')->column();
        foreach ($brand as $key => $value)
        {
            if (isset($tzBrand[$value['state_tree']])) {
                $brand[$key]['name'] = $tzBrand[$value['state_tree']];
            } else {
                unset($brand[$key]);
            }
        }
        //风格分类对象
        $style=GrpStyle::findBySql("select distinct grp_style.`name`,grp_style.id from grp_style,taozhuang,taozhuang_style 
            where taozhuang.app_return = 1 AND taozhuang.sid = taozhuang_style.taozhuang_id AND taozhuang_style.style_id = grp_style.id")->asArray()->all();
        //色系分类对象
        $color=GrpColor::findBySql("SELECT DISTINCT grp_color.id,grp_color.`name` FROM grp_color,taozhuang,taozhuang_color 
            WHERE taozhuang.app_return = 1 AND taozhuang.sid=taozhuang_color.taozhuang_id AND taozhuang_color.color_id=grp_color.id ORDER BY grp_color.id")->asArray()->all();
        
        //套装对象
        $column="DISTINCT taozhuang.sid,
                          taozhuang.`name`,
                          large_img.url as large_img_url,
                          middle_img.url as middle_img_url,
                          small_img.url as small_img_url,
                          taozhuang.price_base as taozhuang_price";
        $tbl_name="taozhuang,sys_image large_img,sys_image middle_img,sys_image small_img";
        $query_str=" taozhuang.app_return = 1 AND taozhuang.img_url_id=large_img.id AND taozhuang.img_small_id=small_img.id AND taozhuang.img_thumb_id=middle_img.id ";
        
        if(isset($get_space_id))
        {
            $column.=",grp_space.`name` as space_name";
            $tbl_name.=",grp_space";
            $query_str.=" AND taozhuang.space_id = ".$get_space_id." AND grp_space.id = taozhuang.space_id";
        }
        if(isset($get_brand_id))
        {
            foreach ($brand as $value){
                if ($get_brand_id==$value['state_tree'])
                {
                    $column.="";
                    $tbl_name.="";
                    $query_str.=" AND taozhuang.state_tree = ".$get_brand_id;
                    break;
                }
            }
        }
        if(isset($get_price))
        {
            $column.=",grp_price.min,grp_price.max";
            $tbl_name.=",grp_price";
            $query_str.=" AND grp_price.id = ".$get_price." AND taozhuang.price_base >= grp_price.min AND taozhuang.price_base < grp_price.max ";
        }
        if(isset($get_style_id))
        {
            $column.=",grp_style.`name` as style_name";
            $tbl_name.=",grp_style,taozhuang_style";
            $query_str.=" AND taozhuang_style.style_id = ".$get_style_id." AND taozhuang_style.taozhuang_id = taozhuang.sid AND grp_style.id = taozhuang_style.style_id";
        }
        if(isset($get_color_id))
        {
            $column.=",grp_color.`name` as color_name";
            $tbl_name.=",grp_color,taozhuang_color";
            $query_str.=" AND taozhuang_color.color_id = ".$get_color_id." AND taozhuang_color.taozhuang_id = taozhuang.sid AND grp_color.id = taozhuang_color.color_id";
        }
        //找我家
        if (isset($get_home_id)) {
            $buildType = BuildType::find()->where(['id' => $get_home_id])->one();
            $tz_list = $buildType->tz_img_list;
            if (!empty($tz_list)) {
                $query_str.=" AND taozhuang.sid IN ($tz_list)";
            }
        }
        $sql_count = "SELECT count(DISTINCT taozhuang.sid) FROM ".$tbl_name." WHERE ".$query_str;
        $result_count=TaoZhuang::findBySql($sql_count)->asArray()->all();
        // print_r($result_count);
        // return;
        $pageSize=yii::$app->request->get('pageSize')?yii::$app->request->get('pageSize'):20;
        $pagination = new Pagination(
            [
                "defaultPageSize" => $pageSize,
                "totalCount" => $result_count[0]['count(DISTINCT taozhuang.sid)']
            ]
        ); 
        $allOrder=[
            'priceasc' => 'taozhuang_price ASC' ,
            'pricedesc' => 'taozhuang_price DESC',
            'datedesc' => 'taozhuang.sid DESC',
            'dateasc' => 'taozhuang.sid ASC'
        ];
        if(isset($get_order))
        {
            $orderStatus = $allOrder[$get_order];
        }else{
            $orderStatus = "taozhuang.sid DESC";
        }
        $sql = "SELECT ".$column." FROM ".$tbl_name." WHERE ".$query_str." 
                ORDER BY ".$orderStatus." 
                limit ".$pagination->offset.",".$pagination->limit;

        $result=TaoZhuang::findBySql($sql)->asArray()->all();
       // print_r($result);return;
        return $this->render('index',[
            'pageSize'=>$pageSize,
            'model'=>$result,
            "pagination"=>$pagination,
            'space'=>$space,
            'get_space_id'=>yii::$app->request->get('space'),
            'style'=>$style,
            'get_style_id'=>yii::$app->request->get('style'),
            'color'=>$color,
            'get_color_id'=>yii::$app->request->get('color'),
            'brand'=>$brand,
            'get_type_id'=>yii::$app->request->get('type'),
            'get_brand_id'=>yii::$app->request->get('brand'),
            'get_class_id'=>yii::$app->request->get('class'),
            'get_type_name'=>isset($get_type_name)?$get_type_name:null,
            'get_brand_name'=>isset($get_brand_name)?$get_brand_name:null,
            'get_class_name'=>isset($get_class_name)?$get_class_name:null,
            'get_order'=>isset($get_order)?$get_order:null,
        ]);
    }
    public function actionTz()
    {
        $sid=intval(Yii::$app->request->get('sid'));
        if(!Yii::$app->user->isGuest){
            //记录足迹
            $userFoot = new LogUserFootprint();
            $userFoot -> uid = Yii::$app->user->identity->id;
            $userFoot -> calltime = time();
            $userFoot -> action = 'set';
            $userFoot -> action_id = Yii::$app->request->get('sid');
            $userFoot -> title = $userFoot -> tz0 ->name;
            $userFoot -> save();
            //记录足迹结束
        }
        $res=TaoZhuangPos::findAll(['tzid'=>$sid,'pay_state'=>1]);
        return $this->render('tz',[
            'sid'=>$sid,
            'isSale'=>empty($res)?false:true,
            'isFavo'=> UserFavourite::find()->where(['uid' => Yii::$app->getUser()->getId(), 'type' => 0, 'type_id' => $sid])->exists(),
        ]);
    }
    //导出数据
    public function actionExportData($param)
    {
        $param = explode(',', $param);
        $data = TaoZhuangPos::find()
            ->select([
                'sys_image.url AS img',
                'sys_item.id AS itemId',
                'grp_brand.name AS brandName',
                'sys_item.gjj_code',
                'sys_item.name AS itemName',
                'base_sys_fabric.name AS fabName',
                'base_sys_material.name AS matName',
                'sys_item.size AS wlsize',
                '`sys_item`.`price_base`',
                'taozhuang_pos.count',
                '`taozhuang_pos`.`count`*`sys_item`.`price_base` AS cost'])
            ->leftJoin(['sys_item'],'sys_item.id=taozhuang_pos.item_id')
            ->leftJoin(['base_sys_fabric'],'base_sys_fabric.id=substring_index(sys_item.fabric_list,\',\',1)')
            ->leftJoin(['base_sys_material'],'base_sys_material.id=substring_index(sys_item.material_list,\',\',1)')
            ->leftJoin(['sys_image'],'sys_image.id=sys_item.img_small_id')
            ->leftJoin(['grp_brand'],'sys_item.brand_id=grp_brand.id')
            ->where(['taozhuang_pos.tzid'=>$param, 'taozhuang_pos.pay_state'=>1])->asArray()->all();
//         if ($data)
//         {
//             //数据处理
//         }
        $header = ['商品图片','单品ID','品牌','单品编码','商品名称','面料','材质','尺寸','单价（元）','数量（件）','总金额（元）']; //导出excel的表头
        CommonFunc::exportData($data, $header, "销售清单");
    }
    public function actionTzPrice()
    {
        $tz=Yii::$app->request->post('tz');
        if (!$tz||empty($tz)){
            return $this->redirect(['tz/index']);
        }
        $obj=json_decode($tz,true);
        $tz_res_info=TaoZhuang::findOne(['sid'=>$obj['info']['id'],'app_return'=>1]);
        if (!$tz_res_info||empty($tz_res_info)){
            return $this->redirect(['tz/index']);
        }
        $obj['info']['name']=$tz_res_info->name;
        $obj['info']['tips']=$tz_res_info->tips;
        $obj['info']['url']=$tz_res_info->middle_img->url;
        $obj['info']['count']=1;
        $exclude=[];$exclude_i=0;
        $tz_res_items=TaoZhuangPos::findAll(['tzid'=>$obj['info']['id']]);
        foreach ($obj['items'] as $i => $obj_item)
        {
            foreach ($tz_res_items as $j => $res_item)
            {
                //如果item_id与pos一致，则单品对应
                if ($obj_item['item_id']==$res_item['item_id']&&$obj_item['pos']==$res_item['pos'])
                {
                    //如果是非卖品则去除
                    if ($res_item['pay_state']==0){
                        unset($obj['items'][$i]);
                    }else{
                        $obj['items'][$i]['count']=intval($res_item['count']);
                        if ($res_item['pay_state']==2)
                        {
                            $exclude[$exclude_i++]=$res_item['item_id'];
                        }
                        $obj['items'][$i]['detail']=new ItemPriceTable($obj_item['item_id']);
                    }
                }
            }
        }
        if (!empty($exclude)){
            $obj['info']['exclude']=$exclude;
        }
        return $this->render("tz_price",[
            'tz'=>$obj
        ]);
    }
    public function actionTzOrder(){
        if (!isset(Yii::$app->user->identity->id))
        {
            return $this->redirect(['site/login']);
        }
        $obj=Yii::$app->request->post('obj');
        $submit_type=Yii::$app->request->post('submit_type');
        if($obj&&$submit_type)
        {
            $obj=json_decode($obj,true);
            $t=TaoZhuang::findOne(['sid'=>$obj['info']['id']]);
            $obj['info']['discount'] = floatval($t['price_custom']);
            $obj['info']['cart_type']=1;
            $t=TaoZhuangPos::findAll(['tzid'=>$obj['info']['id']]);
            $exclude=array();$i=0;
            foreach ($t as $value)
            {
                foreach ($obj['items'] as $item)
                {
                    if ($item['item_id']==$value['item_id']&&$value['pay_state']==2)
                    {
                        $exclude[$i++]=$value['item_id'];
                    }
                }
            }
            if (!empty($exclude))
            {
                $obj['info']['exclude']=$exclude; 
            }
        }
        foreach ($obj['items'] as $key => $value)
        {
            if (isset($value['price_base'])){
                unset($obj['items'][$key]['price_base']);
            }
            if (isset($value['price_custom'])){
                unset($obj['items'][$key]['price_custom']);
            }
            if (isset($value['pos'])){
                unset($obj['items'][$key]['pos']);
            }
        }
        if ($submit_type==1){//提交到购物车
            $shoppingCart=new UserShoppingCart();
            $shoppingCart->type=1;
            $shoppingCart->user_id=Yii::$app->user->identity->id;
            $shoppingCart->jsondata=json_encode($obj,JSON_UNESCAPED_UNICODE);
            $shoppingCart->count=$obj['info']['count'];
            $shoppingCart->createtime=time();
            if ($shoppingCart->save()){
                return $this->render('addStatus',[
                    'msg'=>"提交到购物车成功"
                ]);
            }else{
                return $this->render('addStatus',[
                    'msg'=>"提交到购物车失败"
                ]);
            }
        }
    }
    public function actionTzCalc() {
        $req=Yii::$app->request->post('q');
        if($req=="getPreviewItemsByClass")
        {
            $query="SELECT DISTINCT sys_item.id,
			sys_item.`name`,
			sys_item.img_url_id AS main_img_id,
			sys_item.brand_id,
			grp_brand.`name` AS brand_name,
			sys_item.price_base,
			sys_item.price_discount,
			sys_item.app_return,
			main_img.url AS main_img_url,
			base_sys_preview.img_tz_id AS toushi_img_id,
			base_sys_preview.img_url_id AS fm_large_img_id,
			base_sys_preview.img_small_id AS fm_small_img_id,
			fm_large_img.url AS fm_large_img_url,
			fm_small_img.url AS fm_small_img_url,
			toushi_img.url AS toushi_img_url,
			toushi_img.width AS toushi_img_width,
			toushi_img.height AS toushi_img_height
        	FROM sys_item,sys_image main_img,sys_image toushi_img,sys_image fm_large_img,sys_image fm_small_img,base_sys_preview,grp_brand,sys_item_space
        	WHERE sys_item.class_id=:class_id AND (sys_item.app_return=1 or sys_item.app_return=0) and sys_item.id=base_sys_preview.item_id 
            AND grp_brand.useing=1 AND sys_item.state_tree=0 
    	    AND sys_item.img_url_id=main_img.id AND base_sys_preview.img_tz_id=toushi_img.id AND sys_item.brand_id=grp_brand.id AND sys_item.id=sys_item_space.item_id 
    	    AND fm_large_img.id=base_sys_preview.img_url_id AND fm_small_img.id=base_sys_preview.img_small_id 
    	    AND sys_item_space.space_id=:space_id ORDER BY sys_item.id DESC;";
            $result=SysItem::findBySql($query,[
                ':class_id'=>Yii::$app->request->post('class_id'),
                ':space_id'=>Yii::$app->request->post('space_id')
            ])->asArray()->all();
            $return_arr=array();
            $i=-1;$sign=0;
            foreach ($result as $row)
            {
                if($row["id"]!=$sign)
                {
                    $j=0;$i++;
                    $sign=$row["id"];
                    $return_arr[$i]=array();
                }
                $return_arr[$i][$j]=array(
                    "name"=>$row["name"],
                    "id"  =>$row["id"],
                    "url" =>Yii::$app->params['imgPath0'].$row["toushi_img_url"],
                    "price_base"=>$row["price_base"],
                    "price_discount"=>$row["price_discount"],
                    "main_img_id"=>$row["main_img_id"],
                    "main_img_url"=>Yii::$app->params['imgPath0'].$row["main_img_url"],
                    "brand_id"=>$row["brand_id"],
                    "brand_name"=>$row["brand_name"],
                    "app_return"=>$row["app_return"],
                    "fm_large_img_id"=>$row["fm_large_img_id"],
                    "fm_large_img_url"=>Yii::$app->params['imgPath0'].$row["fm_large_img_url"],
                    "fm_small_img_id"=>$row["fm_small_img_id"],
                    "fm_small_img_url"=>Yii::$app->params['imgPath0'].$row["fm_small_img_url"],
                    "toushi_img_id"=>$row["toushi_img_id"],
                    "toushi_img_url"=>Yii::$app->params['imgPath0'].$row["toushi_img_url"],
                    "width"=>$row["toushi_img_width"],
                    "height"=>$row["toushi_img_height"],
                    "space"
                );
                $query_space="SELECT sys_item_space.space_id,grp_space.`name`,sys_item_space.id 
                    FROM grp_space,sys_item_space 
                    WHERE grp_space.id=sys_item_space.space_id AND sys_item_space.item_id=:item_id";
                $result_space= GrpSpace::findBySql($query_space,[':item_id'=>$row['id']])->asArray()->all();
                $return_arr[$i][$j]["space"]=array();
                foreach ($result_space as $row_space)
                {
                    $return_arr[$i][$j]["space"]["".$row_space["id"]]=array(
                        "name"=>$row_space["name"],
                        "space_id"=>$row_space["space_id"]
                    );
                }
                $j++;
            }
            echo json_encode($return_arr);
        }
        elseif($req=="getClass")
        {
            $tp=intval(Yii::$app->request->post('tp'));
            $return_arr=array();
            if($tp==0)
            {
                $class_id=0;
            }
            elseif($tp==1)
            {
                $class_id=Yii::$app->request->post('class1_id');
            }
            elseif($tp==2)
            {
                $class_id=Yii::$app->request->post('class2_id');
            }
            $query="SELECT * FROM `grp_class` WHERE father=:class_id";
            $result = GrpClass::findBySql($query,[':class_id'=>$class_id])->asArray()->all();
            $i=0;
            foreach ($result as $row)
            {
                $return_arr[$i]=array(
                    "id"=>$row["id"],
                    "name"=>$row["name"]
                );
                $i++;
            }
            echo json_encode($return_arr);
        }
        elseif($req=="getFMList_edit")
        {
            $id=Yii::$app->request->post('id');
            $query="select * from sys_item where id = :id";
            $result=SysItem::findBySql($query,[':id'=>$id])->asArray()->all();
            $row=$result[0];
            //获取面料
            $fab_arr=array();
            $t=$row['fabric_list'];
            if($t=="" || $t==0)
            {}
            else
            {
                $t=str_replace(","," or base_sys_fabric.id = ",$t);
                $query_fabric="select sys_image.url,sys_image.id,base_sys_fabric.name,base_sys_fabric.id as fid 
                    from base_sys_fabric,sys_image 
                    where sys_image.id=base_sys_fabric.img_thumb_id and ( base_sys_fabric.id = ".$t." )";
                $result_fabric=Fabric::findBySql($query_fabric)->asArray()->all();
                $i=0;
                foreach ($result_fabric as $row_fabric)
                {
                    $fab_arr[$i]=array(
                        "url"=>Yii::$app->params['imgPath0'].$row_fabric['url'],
                        "flag"=>"noAction",
                        "uid"=>$row_fabric['fid'],
                        "title"=>$row_fabric['name']
                    );
                    $i++;
                }
            }
            //获取材质
            $mat_arr=array();
            $t=$row['material_list'];
            if($t=="" || $t==0)
            {}
            else
            {
                $t=str_replace(","," or base_sys_material.id = ",$t);
                $query_material="select sys_image.url,sys_image.id,base_sys_material.name,base_sys_material.id as mid from base_sys_material,sys_image 
                    where sys_image.id=base_sys_material.img_thumb_id and ( base_sys_material.id = ".$t." )";
                $result_material=Material::findBySql($query_material)->asArray()->all();
                $i=0;
                foreach ($result_material as $row_material)
                {
                    $mat_arr[$i]=array(
                        "url"=>Yii::$app->params['imgPath0'].$row_material['url'],
                        "flag"=>"noAction",
                        "uid"=>$row_material['mid'],
                        "title"=>$row_material['name']
                    );
                    $i++;
                }
            }
            //获取材质面料对应图
            $query_fm="SELECT base_sys_preview.id,base_sys_preview.fid,base_sys_preview.mid,base_sys_preview.img_url_id,base_sys_preview.img_tz_id,a.url AS img_url,b.url AS toushi_url 
                FROM base_sys_preview,sys_image a,sys_image b WHERE base_sys_preview.item_id=:id AND a.id=base_sys_preview.img_url_id AND b.id=base_sys_preview.img_tz_id;";
            $result_fm=ItemPreview::findBySql($query_fm,[':id'=>$id])->asArray()->all();
            $i=0;
            $angle_arr=array();
            foreach ($result_fm as $row_fm)
            {
                $angle_arr[$i]=array(
                    "uid"=>$row_fm["id"],
                    "flag"=>"noAction",
                    "img_url"=>Yii::$app->params['imgPath0'].$row_fm['img_url'],
                    "toushi_url"=>Yii::$app->params['imgPath0'].$row_fm['toushi_url'],
                    "fid"=>$row_fm['fid'],
                    "mid"=>$row_fm['mid'],
                    "img_id"=>$row_fm['img_url_id'],
                    "toushi_id"=>$row_fm['img_tz_id']
                );
                $i++;
            }
            $return_arr=array(
                "fabric"=>$fab_arr,
                "material"=>$mat_arr,
                "angle"=>$angle_arr
            );
            echo json_encode($return_arr);
        }
        elseif($req=="getImageList_edit")
        {
            $pos=Yii::$app->request->post('pos');
            $tzid=Yii::$app->request->post('tz');
            $query="SELECT taozhuang_pos.`order`,sys_image.url,img2.id AS main_img_id,img2.url AS main_img_url,sys_image.width,sys_image.height,sys_item.`name`,
                sys_item.price_base,sys_item.price_discount,grp_brand.id AS brand_id,grp_brand.`name` AS brand_name,sys_item.app_return,
                taozhuang_pos.anchor_x,taozhuang_pos.anchor_y,taozhuang_pos.x,taozhuang_pos.y,taozhuang_pos.zoom,taozhuang_pos.father,taozhuang_pos.mirror,
                sys_item.id AS itemid,class3.id AS class3_id,class3.`name` AS class3_name,class2.id AS class2_id,class2.`name` AS class2_name,
                class1.id AS class1_id,class1.`name` AS class1_name FROM sys_image,sys_image img2,taozhuang_pos,sys_item,grp_brand,
                grp_class class3 LEFT JOIN (grp_class class2 LEFT JOIN grp_class class1 ON class2.father=class1.id) ON class3.father=class2.id 
                WHERE class3.id=sys_item.class_id AND sys_item.brand_id=grp_brand.id AND sys_item.img_url_id=img2.id AND sys_item.id=taozhuang_pos.item_id 
                AND taozhuang_pos.img_id=sys_image.id AND taozhuang_pos.tzid = :tzid AND taozhuang_pos.pos =:pos";
            $result = SysItem::findBySql($query,[':tzid'=>$tzid,':pos'=>$pos])->asArray()->all();
            
            $arr=array();
            $i=0;
            foreach ($result as $row)
            {
                
                if($row["class1_id"]==NULL)
                {
                    if($row["class2_id"]!=NULL)
                    {
                        $row["class1_id"]=$row["class2_id"];
                        $row["class1_name"]=$row["class2_name"];
                        $row["class2_id"]=$row["class3_id"];
                        $row["class2_name"]=$row["class3_name"];
                        $row["class3_id"]=NULL;
                        $row["class3_name"]=NULL;
                    }
                    else
                    {
                        $row["class1_id"]=$row["class3_id"];
                        $row["class1_name"]=$row["class3_name"];
                        $row["class3_id"]=NULL;
                        $row["class3_name"]=NULL;
                    }
                }
                
                $arr[$i]=array(
                    "flag"=>"noAction",
                    "modify"=>0,
                    "index"=>(int)$row["order"],
                    "url"=>Yii::$app->params['imgPath0'].$row['url'],
                    "main_img_id"=>$row["main_img_id"],
                    "main_img_url"=>Yii::$app->params['imgPath0'].$row['main_img_url'],
                    "title"=>$row['name'],
                    "price_base"=>$row['price_base'],
                    "price_discount"=>$row['price_discount'],
                    "selected"=>0,
                    "brand_name"=>$row['brand_name'],
                    "brand_id"=>$row['brand_id'],
                    "app_return"=>$row['app_return'],
                    "fma_required"=>0,
                    "img_one"=>"",
                    "img_one_div"=>"",
                    "img"=>"",
                    "img_one_title"=>"",
                    "space",
                    "filter"=>array(
                        "grayscale"=>0,
                        "sepia"=>0,
                        "saturate"=>100,
                        "hue-rotate"=>0,
                        "invert"=>0,
                        "opacity"=>100,
                        "brightness"=>100,
                        "contrast"=>100,
                        "blur"=>0,
                    ),
                    "dataset"=>array(
                        "pos"=>$pos,
                        "father"=>intval($row['father']),
                        "width"=>intval($row['width']),
                        "height"=>intval($row['height']),
                        "zoom"=>floatval($row['zoom']),
                        "left"=>intval($row['x']),
                        "top"=>intval($row['y']),
                        "anchor_x"=>floatval($row['anchor_x']),
                        "anchor_y"=>floatval($row['anchor_y']),
                        "uid"=>$row['itemid'],
                        "mirror"=>intval($row['mirror'])
                    )
                );
                
                $query_space="SELECT sys_item_space.space_id,grp_space.`name`,sys_item_space.id FROM grp_space,sys_item_space 
                    WHERE grp_space.id=sys_item_space.space_id AND sys_item_space.item_id=:item_id";
                $result_space= GrpSpace::findBySql($query_space,[':item_id'=>$row['itemid']])->asArray()->all();
                foreach ($result_space as $row_space)
                {
                    $arr[$i]["space"]["".$row_space["id"]]=array(
                        "name"=>$row_space["name"],
                        "space_id"=>$row_space["space_id"]
                    );
                }
                $i++;
            }
            echo json_encode($arr,JSON_UNESCAPED_UNICODE);
        }
    }
}